import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'entity/user.dart';
import 'main.dart';
import 'objectbox.g.dart';

class AddUserPage extends StatefulWidget {
  const AddUserPage({super.key});

  @override
  State<AddUserPage> createState() => _AddUserPageState();
}

class _AddUserPageState extends State<AddUserPage> {
  late Box<User> _userBox;
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _userBox = objectBox.store.box<User>();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('添加用户'),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          const SizedBox(height: 30,),
          Padding(
            padding: const EdgeInsets.all(10),
            child: TextField(
              controller: _controller,
              decoration: const InputDecoration(
                  label: Text('用户名'),
                  hintText: '请输入用户名',
                  enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.lightBlueAccent, width: 1)
                  ),
                  focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.lightBlueAccent, width: 1)
                  )
              ),
            ),
          ),
          const SizedBox(height: 20,),
          Container(
            width: double.infinity,
            margin: const EdgeInsets.only(left: 20, right: 20),
            child: ElevatedButton(
              onPressed: () {
                var name = _controller.text;
                if(name.isEmpty) {
                  Fluttertoast.showToast(msg: '请输入用户名');
                  return;
                }
                User user = User();
                user.username = name;
                _userBox.put(user);
                Get.back(result: true);
              },
              child: const Padding(
                padding: EdgeInsets.all(10),
                child: Text(
                  '添加用户',
                  style: TextStyle(fontSize: 18),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}